package com.controller;

import com.aop.SystemLog;
import com.dao.StudentDao;
import com.dto.DTO;
import com.entity.Sc;
import com.entity.Student;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.service.StudentService;
import com.utils.ContextUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.WebApplicationContext;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;


@Controller //@Controller注解是用spring容器生成 对象 默认对象名 studentController
@RequestMapping("/studentController") //@RequestMapping 用户请求查找该资源使用的名字 网名 默认  /studentController
public class StudentController {
	@Resource
	StudentService studentService;
	@RequiresPermissions("student:getAll")
	@RequestMapping("/getAllStudent")
	@ResponseBody //把方法的返回值按json转换之后 输出到浏览器
    public DTO<Student> getAllStudent() throws Exception{
    	System.out.println("查询全部学生");
    	return studentService.getAllStudents();
    }

	@RequestMapping("/selectBySnoWithScs/{sno}")
	@ResponseBody //把方法的返回值按json转换之后 输出到浏览器
	public DTO<Student> selectBySnoWithScs(@PathVariable("sno") String sno) throws Exception{
		System.out.println("查询学生选课");
		return studentService.selectBySnoWithScs(sno);
	}

	@RequestMapping("/selectBySnoWithClazz/{sno}")
	@ResponseBody //把方法的返回值按json转换之后 输出到浏览器
	public DTO<Student> selectBySnoWithClazz(@PathVariable("sno") String sno) throws Exception{
		System.out.println("查询学生选课");
		return studentService.selectBySnoWithClazz(sno);
	}

	@RequiresPermissions("student:selectBySnoWithScsAndClazz")
	@RequestMapping("/selectBySnoWithScsAndClazz/{sno}")
	@ResponseBody //把方法的返回值按json转换之后 输出到浏览器
	@SystemLog(module = "学生管理",methods = "根据学号查询学生附带该名学生的选课信息和班级信息")
	public DTO<Student> selectBySnoWithScsAndClazz(@PathVariable("sno") String sno,HttpServletRequest request,HttpServletResponse response) throws Exception{
		System.out.println("查询学生选课111");
		DTO<Student> dto = studentService.selectBySnoWithScsAndClazz(sno);
		saveSelectCourseCookieProcess(dto.getT(),request,response);
		return  dto;
	}

	@RequestMapping("/selectBySnoWithScsAndCourse/{sno}")
	@ResponseBody //把方法的返回值按json转换之后 输出到浏览器
	public DTO<Student> selectBySnoWithScsAndCourse(@PathVariable("sno") String sno) throws Exception{
		System.out.println("查询学生选课带课程信息");
		return studentService.selectBySnoWithScsAndCourse(sno);
	}

	@RequestMapping("/selectBySnoWithClazzANDTeacher/{sno}")
	@ResponseBody //把方法的返回值按json转换之后 输出到浏览器
	public DTO<Student> selectBySnoWithClazzANDTeacher(@PathVariable("sno") String sno) throws Exception{
		System.out.println("查询学生班级和班主任");
		return studentService.selectBySnoWithClazzANDTeacher(sno);
	}



	@RequestMapping("/deleteStudentBySno/{sno}")
	@ResponseBody
    public DTO<Student> deleteStudentBySno(@PathVariable("sno") String sno) throws Exception{//如何从页面传入参数到方法 用这个注解绑定变量@PathVariable
    	System.out.println(sno+"删除学生");
    	return studentService.deleteStudentBySno(sno);
    }
	@RequestMapping("/addSc")
	@ResponseBody
	public DTO<Student> addSC(Sc sc) throws Exception{
		return studentService.addSC(sc);
	}

	@RequestMapping("/saveSelectCourseCookie")
	@ResponseBody
	public DTO<Student> saveSelectCourseCookie(@RequestBody Student student,HttpServletRequest request,HttpServletResponse response) throws Exception{
		return saveSelectCourseCookieProcess(student, request, response);
	}

	public DTO<Student> saveSelectCourseCookieProcess(Student student,HttpServletRequest request,HttpServletResponse response) throws JsonProcessingException, UnsupportedEncodingException {
		//cookie是以key value形式存放在浏览器的文本
		DTO dto = new DTO(200,"选课保存成功");
		if(student.getSno()!=null) {
			ObjectMapper objectMapper = new ObjectMapper();
            List<Sc> scs = new ArrayList<>(student.getScs());
			for (Sc sc : student.getScs()) {
				Cookie scsCookie = new Cookie("student" + student.getSno() + "_" + sc.getScno(), URLEncoder.encode(objectMapper.writeValueAsString(sc), "UTF-8"));

				//studentCookie.setMaxAge(30*24*60*60);   //存活期为一个月 30*24*60*60
				scsCookie.setPath("/");
				scsCookie.setDomain("localhost");
				scsCookie.setMaxAge(2 * 24 * 60 * 60);   //存活期为2天 2*24*60*60
				response.addCookie(scsCookie);

			}
			student.setScs(null);
			Cookie studentCookie = new Cookie("student" + student.getSno(), URLEncoder.encode(objectMapper.writeValueAsString(student), "UTF-8"));
			studentCookie.setPath("/");
			studentCookie.setDomain("localhost");
			studentCookie.setMaxAge(2 * 24 * 60 * 60);   //存活期为2天 2*24*60*60
			response.addCookie(studentCookie);
			student.setScs(scs);
		}else{
			dto.setCode(406);
			dto.setMsg("缺少必要的参数，非法操作");
		}
		return dto;
	}

	@RequestMapping("/getSelectCourseCookie/{sno}")
	@ResponseBody
	public DTO<Student> getSelectCourseCookie(@PathVariable("sno") String sno, HttpServletRequest request, HttpServletResponse response) throws Exception{
		//cookie是以key value形式存放在浏览器的文本
		ObjectMapper objectMapper = new ObjectMapper();
		DTO dto = new DTO(200, "cookie选课获取成功");
		Cookie[] cookies = request.getCookies();
		Student student = null;
		if(Optional.ofNullable(cookies).isPresent()){
			List<Sc> scs = new ArrayList<Sc>();
		for(Cookie cookie :cookies){
			if(cookie.getName().indexOf("student" + sno+"_")>=0){
				Sc sc = objectMapper.readValue(URLDecoder.decode(cookie.getValue()), Sc.class);
				scs.add(sc);
			}
			if(cookie.getName().equals("student" + sno)){
				student = objectMapper.readValue(URLDecoder.decode(cookie.getValue()), Student.class);
			}

		}
			if(Optional.ofNullable(student).isPresent()){
				student.setScs(scs);
				dto.setT(student);
			}
		}
	if(!Optional.ofNullable(student).isPresent()){
			dto.setCode(404);
			dto.setMsg("没有cookie");
		}


		return dto;
	}



}
